package com.dawn.module.mp.dal.dataobject.msgtemplatelog;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import lombok.*;
import java.util.*;
import java.time.LocalDateTime;
import java.time.LocalDateTime;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.*;
import com.dawn.framework.mybatis.core.dataobject.BaseDO;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;

/**
 * 模板消息记录 DO
 *
 * @author mamba 4 left
 */
@TableName(value = "mp_msg_template_log", autoResultMap = true)
@KeySequence("mp_msg_template_log_seq") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库，可不写。
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MsgTemplateLogDO extends BaseDO {

    /**
     * 主键
     */
    @TableId
    private Long id;
    /**
     * appid
     */
    private String appid;
    /**
     * 微信公众号ID
     */
    private Long accountId;
    /**
     * 用户openid
     */
    private String touser;
    /**
     * templateid
     */
    private String templateId;
    /**
     * 消息数据
     */
    @TableField(typeHandler = JacksonTypeHandler.class)
    private JSONArray data;
    /**
     * 消息链接
     */
    private String url;
    /**
     * 小程序信息
     */
    @TableField(typeHandler = JacksonTypeHandler.class)
    private JSONObject miniprogram;
    /**
     * 发送时间
     */
    private LocalDateTime sendTime;
    /**
     * 发送结果
     */
    private String sendResult;
    /**
     * 发送状态
     */
    private Boolean status;
    /**
     * 模板消息
     */
    private String message;

    public MsgTemplateLogDO(WxMpTemplateMessage msg, String appid, String sendResult, Boolean status) {
        this.appid = appid;
        this.touser = msg.getToUser();
        this.templateId = msg.getTemplateId();
        this.url = msg.getUrl();
        if(msg.getMiniProgram() != null && StringUtils.isNoneBlank(msg.getMiniProgram().getAppid())) {
            this.miniprogram = JSONObject.parseObject(JSON.toJSONString(msg.getMiniProgram()));
        }
        this.data = JSONArray.parseArray(JSON.toJSONString(msg.getData()));
        this.sendTime = LocalDateTime.now();
        this.sendResult = sendResult;
        this.status = status;
        this.message = JSON.toJSONString(msg);
    }
}
